import router from "@/router/index.js";
import {useUserStore} from "@/store/module/userStore.js";
import {useMenu} from "@/store/module/menuStore.js";
import {ElLoading} from "element-plus";

const whiteList = ['/login'];
let loadingInstance = null;
// vue-router4 好像不是返回next()放行，返回一个boolean值
router.beforeEach(async (to) => {
    loadingInstance = ElLoading.service({
        lock: true,
        // text: '正在加载数据，请稍候~',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    const userStore = useUserStore();
    // 白名单直接放行，无需登录
    if (whiteList.some(item => to.path === item)) {
        return true;
    }
    if (userStore.getToken) {
        const {menu,generateMenus} = useMenu();
        if(!menu.length){
            await generateMenus();
            return to.fullPath
        }else {
            // return true;
        }
    } else {
        return {
            name: 'login',
            query: {
                redirect: to.fullPath
            },
            replace: true
        }
    }
});

router.afterEach(to=>{
    loadingInstance.close()
})